package cn.easybuy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.easybuy.entity.MyOrder;
import cn.easybuy.service.BuyCarService;
import cn.easybuy.service.impl.BuyCarServiceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@WebServlet("/BuyCarServlet")
public class BuyCarServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public BuyCarServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		BuyCarService buyCarService=new BuyCarServiceImpl();
		String opr = request.getParameter("opr");
		HttpSession session=request.getSession();
		if("buyCarlist".equals(opr)){
			String loginName=(String) session.getAttribute("userName");
			try {
				List<MyOrder> buyCarlist=buyCarService.getBuyCarlistByLoginName(loginName);
				session.setAttribute("buyCarlist", buyCarlist);
				String page=request.getParameter("page");
				if("two".equals(page)){
					List<MyOrder> list=new ArrayList<MyOrder>();
					String shopCar=request.getParameter("shopcar");
					Float totalPrice=new Float(request.getParameter("totalPrice"));
					int totalScore=new Integer(request.getParameter("totalScore"));
					JSONArray json = (JSONArray) JSONArray.parse(shopCar);
					for(Object obj:json){
						MyOrder  order=new MyOrder();
						JSONObject jo = (JSONObject)obj;
					    order.setId(jo.getInteger("id"));
					    order.setCost(jo.getInteger("cost"));
					    order.setQuantity(jo.getInteger("num"));
					    order.setScore(jo.getInteger("score"));
					    list.add(order);
					}
					int result=buyCarService.updateList(list);
					if(result>0){
						buyCarlist=buyCarService.getBuyCarlistByLoginName(loginName);
						session.setAttribute("buyCarlist", buyCarlist);
						session.setAttribute("totalPrice", totalPrice);
						session.setAttribute("totalScore", totalScore);
						response.sendRedirect("BuyCar_Two.jsp");
					}
				}else if("three".equals(page)){
					response.sendRedirect("BuyCar_Three.jsp");
				}else if("one".equals(page)){					
					response.sendRedirect("BuyCar.jsp");
				}else if("ajax".equals(page)){
					out.print(JSON.toJSON(buyCarlist));
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else if("count".equals(opr)){
			String loginName=(String) session.getAttribute("userName");
			try {
				int count=buyCarService.getBuyCarCountByLoginName(loginName);
				out.print(count);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if("del".equals(opr)){
			boolean  flag=false;
			int id=new Integer(request.getParameter("id"));
			try {
				int result=buyCarService.delId(id);
				if(result>0){
					flag=true;
				} else {
					flag=false;
				}
				out.print(JSON.toJSON(flag));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else if("delAll".equals(opr)){
			boolean  flag=false;
			String name=request.getParameter("userName");
			try {
				int result=buyCarService.delAll(name);
				if(result>0){
					flag=true;
				} else {
					flag=false;
				}
				out.print(JSON.toJSON(flag));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else if("stock".equals(opr)){
			boolean flag=true;
			int num= new Integer(request.getParameter("num"));
			int id=new Integer(request.getParameter("id"));
			try {
				int stock=buyCarService.stock(id);
				if(stock<num){
					flag=false;
				}
				Object [] obj={flag,stock};
				out.print(JSON.toJSONString(obj));
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		out.flush();
		out.close();
	}
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
